﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Derbster.Domain;

namespace Derbster.Mock
{
    /// <summary>
    /// This is an in-memory version of repository. Note, we don't use the singleton pattern here. 
    /// Instead, we count on Unity to control the lifecycle of these objects. By default, we use
    /// a container-controlled lifecycle, so only one instance of a repository is returned per container.
    /// </summary>
    public class MockTeamRepository : ITeamRepository
       
    {
        private readonly ObservableCollection<Team> _all;

        public MockTeamRepository()
        {
            _all = new ObservableCollection<Team>();
        }

        public Team Create(string name)
        {
            Team newTeam = new Team(name);

            newTeam.TeamId = _all.Count + 1;
            _all.Add(newTeam);

            return newTeam;
        }

        public Team Create(string name, string location)
        {
            Team newTeam = new Team(name,location);

            newTeam.TeamId = _all.Count + 1;
            _all.Add(newTeam);

            return newTeam;
        }

        public Team FindById(int id)
        {
            return _all.SingleOrDefault(m => m.TeamId == id);
        }

        public Team FindByName(string name)
        {
            return _all.SingleOrDefault(m => m.Name.ToLower() == name.ToLower());
        }

        public IEnumerable<Team> FindByLocation(string location)
        {
            return _all.Where(m => !String.IsNullOrWhiteSpace(m.Location) && m.Location.ToLower() == location.ToLower()).AsEnumerable();
        }

        public Team Update(Team team)
        {
            return team;
        }

        public void Delete(Team team)
        {
            _all.Remove(team);
        }

        public void Dispose()
        {
            return;
        }

        public IEnumerator<Team> GetEnumerator()
        {
            return _all.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public Expression Expression
        {
            get
            {
                return _all.AsQueryable().Expression;
            }
        }

        public Type ElementType
        {
            get
            {
                return _all.AsQueryable().ElementType;
            }
        }

        public IQueryProvider Provider
        {
            get
            {
                return _all.AsQueryable().Provider;
            }
        }
    }
}
